package com.ruoyi.web.controller.system;

import com.ruoyi.web.service.FileService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * 注册验证
 *
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController {
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    FileService fileService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user) {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 帖子图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("wx/register/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult upload(@RequestPart("file") MultipartFile file, String username) throws Exception {
//        System.err.println(file.getOriginalFilename());
        String OriginalFilename = file.getOriginalFilename();
        int lastIndexOfDot = OriginalFilename.lastIndexOf(".");
        String lastName = (lastIndexOfDot == -1) ? "" : OriginalFilename.substring(lastIndexOfDot + 1);// 后缀

        String fileName = username + "." + lastName;
        String uploadFlag = fileService.upload(file, "src/avatar/" + fileName);
        if (uploadFlag == "上传成功") {
            // 图片url存redis中,存三小时
            URL url = fileService.getUrl("src/avatar/" + fileName);
            redisTemplate.opsForValue().set(username,url,3,TimeUnit.HOURS);
            return AjaxResult.success("上传成功");
        } else {
            return AjaxResult.error("上传失败");
        }
    }
}
